<?php
// +----------------------------------------------------------------------
// | 众联TK架构 [ ZoomTk ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2037 成都众联思索科技有限公司 [ http://www.zoomtk.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.sopvip.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\mall\home\seller;

use app\mall\common\Base;

/**
 * 卖家中心控制器
 * @package app\cms\admin
 */
class BaseSeller extends Base
{
    //店铺信息
    protected $store_info = array();
    //店铺等级
    protected $store_grade = array();

    public function _initialize()
    {
        parent::_initialize();
        //输出会员信息
        $this->getMemberAndGradeInfo(false);
        if (UID && session('store_id')) {
           // hook('im_chat');
            // 验证店铺是否存在
            $model_store = Model('store');
            $this->store_info = $model_store->getStoreInfoByID(session('store_id'));
            session('is_own_shop',$this->store_info['is_own_shop']);
            $_c=explode('.',$this->request->controller());
            $this->assign('act', $_c[1]);
            if (empty($this->store_info)) {
                $this->error('您的店铺不存在或被禁用', url('/'));
            }
            // 店铺关闭标志
            if (intval($this->store_info['store_state']) === 0) {
                $this->assign('store_closed', true);
                $this->assign('store_close_info', $this->store_info['store_close_info']);
            }
            // 店铺等级
            if ($this->store_info['is_own_shop']) {
                $this->store_grade = array(
                    'sg_id' => '0',
                    'sg_name' => '自营店铺专属等级',
                    'sg_goods_limit' => '0',
                    'sg_album_limit' => '0',
                    'sg_space_limit' => '999999999',
                    'sg_template_number' => '6',
                    // see also store_settingControl.themeOp()
                    // 'sg_template' => 'default|style1|style2|style3|style4|style5',
                    'sg_price' => '0.00',
                    'sg_description' => '',
                    'sg_function' => 'editor_multimedia',
                    'sg_sort' => '0',
                );
            } else {
//                $store_grade = cache('store_grade');
//                $this->store_grade = $store_grade[$this->store_info['grade_id']];
            }
            // 卖家菜单
            if (session('seller_menu')) {
                $seller_menu = session('seller_menu');
            } else {
                if (session('is_admin')) {
                    session('seller_group_name', '管理员');
                    session('seller_smt_limits', false);
                } else {
                    $model_seller_group = Model('seller_group');
                    $seller_group_info = $model_seller_group->getSellerGroupInfo(array('group_id' => session('seller_group_id')));
                    session('seller_group_name', $seller_group_info['group_name']);
                    session('seller_smt_limits', explode(',', $seller_group_info['smt_limits']));
                }
                $seller_menu = $this->getSellerMenuList(session('is_admin'), explode(',', $seller_group_info['limits']));
                session('seller_menu', $seller_menu['seller_menu']);
                session('seller_function_list', $seller_menu['seller_function_list']);
//                //快捷菜单
//                if (!empty(session('seller_quicklink'))) {
//                    $quicklink_array = explode(',', session('seller_quicklink'));
//                    foreach ($quicklink_array as $value) {
//                        session('seller_quicklink' . [$value], $value);
//                    }
//                }
            }
            $this->assign('menu', $seller_menu);
            // 当前菜单
            $current_menu = $this->_getCurrentMenu(session('seller_function_list'));
            $this->assign('current_menu', $current_menu);
            // 左侧菜单
            if ($_c[1] == 'index') {
                if (!empty(session('seller_quicklink'))) {
                    $left_menu = array();
                    foreach (session('seller_quicklink') as $value) {
                        $left_menu[] = session('seller_function_list')[$value];
                    }
                }
            } else {
                $left_menu = session('seller_menu')[$current_menu['model']]['child'];
            }
            $this->assign('left_menu', $left_menu);
            $this->assign('seller_quicklink', $_SESSION['seller_quicklink']);
            $week = array("日", "一", "二", "三", "四", "五", "六");
            $tday_time = array();
            $tday_time['day_data'] = date("Y年m月d日", time());
            $tday_time['tday_week'] = $week[date("w")];
            $this->assign('left_menu', $left_menu);
            $this->assign('tday_time', $tday_time);
            //   $this->checkStoreMsg();  //消息
        } else {
            $this->redirect(url('/'));
        }
    }
    /**
     * 输出会员等级
     * @param bool $is_return 是否返回会员信息，返回为true，输出会员信息为false
     */
    protected function getMemberAndGradeInfo($is_return = false)
    {
        $member_info = array();
        //会员详情及会员级别处理
        if (session('member_id')) {
            $model_member = Model('member');
            $member_info = $model_member->getMemberInfoByID($_SESSION['member_id']);
            if ($member_info) {
                $member_gradeinfo = $model_member->getOneMemberGrade(intval($member_info['member_exppoints']));
                $member_info = array_merge($member_info, $member_gradeinfo);
                $member_info['security_level'] = $model_member->getMemberSecurityLevel($member_info);
            }
        }
        if ($is_return == true) {//返回会员信息
            return $member_info;
        } else {//输出会员信息
            $this->assign('member_info', $member_info);
        }
    }

    /**
     * 记录卖家日志
     *
     * @param $content 日志内容
     * @param $state 1成功 0失败
     */
    protected function recordSellerLog($content = '', $state = 1)
    {
        $seller_info = array();
        $seller_info['log_content'] = $content;
        $seller_info['log_time'] = TIMESTAMP;
        $seller_info['log_seller_id'] = $_SESSION['seller_id'];
        $seller_info['log_seller_name'] = $_SESSION['seller_name'];
        $seller_info['log_store_id'] = $_SESSION['store_id'];
        $seller_info['log_seller_ip'] = getIp();
        $seller_info['log_url'] = $_GET['s'] . '&' . $_GET['op'];
        $seller_info['log_state'] = $state;
        $model_seller_log = Model('seller_log');
        $model_seller_log->addSellerLog($seller_info);
    }
    /**
     * 记录店铺费用
     *
     * @param $cost_price 费用金额
     * @param $cost_remark 费用备注
     */
    protected function recordStoreCost($cost_price, $cost_remark)
    {
        // 平台店铺不记录店铺费用
        if (checkPlatformStore()) {
            return false;
        }
        $model_store_cost = Model('store_cost');
        $param = array();
        $param['cost_store_id'] = $_SESSION['store_id'];
        $param['cost_seller_id'] = $_SESSION['seller_id'];
        $param['cost_price'] = $cost_price;
        $param['cost_remark'] = $cost_remark;
        $param['cost_state'] = 0;
        $param['cost_time'] = TIMESTAMP;
        $model_store_cost->addStoreCost($param);
        // 发送店铺消息
        $param = array();
        $param['code'] = 'store_cost';
        $param['store_id'] = $_SESSION['store_id'];
        $param['param'] = array(
            'price' => $cost_price,
            'seller_name' => $_SESSION['seller_name'],
            'remark' => $cost_remark
        );

        QueueClient::push('sendStoreMsg', $param);
    }

    protected function getSellerMenuList($is_admin, $limits)
    {
        $seller_menu = array();
        if (intval($is_admin) !== 1) {
            $menu_list = $this->_getMenuList();
            foreach ($menu_list as $key => $value) {
                foreach ($value['child'] as $child_key => $child_value) {
                    if (!in_array($child_value['url'], $limits)) {
                        unset($menu_list[$key]['child'][$child_key]);
                    }
                }

                if (count($menu_list[$key]['child']) > 0) {
                    $seller_menu[$key] = $menu_list[$key];
                }
            }
        } else {
            $seller_menu = $this->_getMenuList();
        }
        $seller_function_list = $this->_getSellerFunctionList($seller_menu);
        return array('seller_menu' => $seller_menu, 'seller_function_list' => $seller_function_list);
    }

    private function _getCurrentMenu($seller_function_list)
    {
        $_c=explode('.',$this->request->controller());
        $current_menu = $seller_function_list[$_c[1]];
        if (empty($current_menu)) {
            $current_menu = array(
                'model' => 'index',
                'model_name' => '首页'
            );
        }
        return $current_menu;
    }

    private function _getMenuList()
    {
        $menu_list = array(
            'goods' => array('name' => '商品管理', 'child' => array(
                array('name' => '商品发布', 'act'=>'goodsadd','url' => url('seller.goodsadd/index')),
                array('name' => '出售中的商品', 'act'=>'goodsonline', 'url' => url('seller.goodsonline/index')),
                array('name' => '仓库中的商品', 'act'=>'goodsoffline', 'url' => url('seller.goodsoffline/index')),
               //     array('name' => '预约/到货通知', 'act'=>'seller.appoint', 'url' => url('seller.appoint/index')),
                //   array('name' => '关联版式',  'act'=>'store_plate','url'=>url('store_plate/index')),
                array('name' => '商品规格', 'act'=>'spec', 'url' => url('seller.spec/index')),
                //    array('name' => '图片空间', 'act'=>'store_album', 'url'=>url('store_album/album_cate')),
            )),
            'order' => array('name' => '订单物流', 'child' => array(
                array('name' => '交易订单', 'act'=>'order', 'url' => url('seller.order/index')),
                array('name' => '发货', 'act'=>'deliver', 'url' => url('seller.deliver/index')),
                array('name' => '发货设置', 'act'=>'deliverset', 'url' => url('seller.deliverset/daddress_list')),
                array('name' => '运单模板',  'act'=>'waybill','url' => url('seller.waybill/waybill_manage')),
                array('name' => '物流工具',  'act'=>'transport','url' => url('seller.transport/index')),
            )),
            'store' => array('name' => '店铺', 'child' => array(
                array('name' => '店铺设置', 'act'=>'setting', 'url' => url('seller.setting/setting')),
                array('name' => '店铺导航', 'act'=>'navigation', 'url' => url('seller.navigation/navigation_list')),
                array('name' => '店铺信息', 'act'=>'storeinfo', 'url' => url('seller.storeinfo/bind_class')),
                array('name' => '店铺分类', 'act'=>'goodsclass', 'url' => url('seller.goodsclass/index')),
                //  array('name' => '店铺广告',' 'act'=>'seller.goodsad',url'=>url('seller.goodsad/index')),
                // array('name' => '手机设置', 'act'=>'seller.mbspecial','url'=>url('seller.mbspecial/index')),
            )),
            'consult' => array('name' => '售后服务', 'child' => array(
                array('name' => '咨询管理', 'act'=>'consult', 'url' => url('seller.consult/consult_list')),
                array('name' => '投诉管理', 'act'=>'complain', 'url' => url('seller.complain/list')),
             //   array('name' => '退款记录', 'act'=>'seller.refund', 'url' => url('seller.refund/index')),
             //   array('name' => '退货记录',  'act'=>'seller.return','url' => url('seller.return/index')),
            )),
            'statistics' => array('name' => '统计结算', 'child' => array(
                array('name' => '店铺概况', 'act'=>'statisticsgeneral', 'url' => url('seller.statisticsgeneral/general')),
                array('name' => '商品分析', 'act'=>'statisticsgoods', 'url' => url('seller.statisticsgoods/goodslist')),
//                array('name' => '运营报告',  'act'=>'statisticssale','url' => url('seller.statisticssale/sale')),
                array('name' => '行业分析', 'act'=>'statisticsindustry', 'url' => url('seller.statisticsindustry/hot')),
//                array('name' => '流量统计', 'act'=>'statisticsflow', 'url' => url('seller.statisticsflow/storeflow')),
                array('name' => '实物结算', 'act'=>'bill', 'url' => url('seller.bill/index')),
//                array('name' => '虚拟结算',  'act'=>'','url'=>url('seller.vrbill/index')),
//                array('name' => '奖金结算', 'act'=>'', 'url' => url('seller.selleraward/index')),
//                array('name' => '收银结算', 'act'=>'', 'url' => url('seller.cashieraward/index')),
//                array('name' => '门店结算', 'act'=>'', 'url' => url('seller.chainaward/index')),
            )),
//            'account' => array('name' => '账号', 'child' => array(
//                array('name' => '账号列表', 'act'=>'', 'url' => url('seller.account/account_list')),
//                array('name' => '账号组',  'act'=>'','url' => url('seller.accountgroup/group_list')),
//                array('name' => '账号日志', 'act'=>'', 'url' => url('seller.sellerlog/log_list')),
//                array('name' => '店铺消费', 'act'=>'', 'url' => url('seller.storecost/cost_list')),
//                array('name' => '门店管理',  'act'=>'','url' => url('seller.storechain/index')),
//            )),
        );
        return $menu_list;
    }

    /***
     * @param $menu_list
     * @return array
     * 输出菜单
     */
    private function _getSellerFunctionList($menu_list)
    {
        $format_menu = array();
        foreach ($menu_list as $key => $menu_value) {
            foreach ($menu_value['child'] as $sk=>$submenu_value) {
                $format_menu[$submenu_value['act']] = array(
                    'model' => $key,
                    'model_name' => $menu_value['name'],
                    'name' => $submenu_value['name'],
                    'url' => $submenu_value['url'],
                );
            }
        }
        return $format_menu;
    }

    /**
     * 自动发布店铺动态
     *
     * @param array $data 相关数据
     * @param string $type 类型 'new','coupon','xianshi','mansong','bundling','groupbuy'
     *            所需字段
     *            new       goods表'             goods_id,store_id,goods_name,goods_image,goods_price,goods_freight
     *            xianshi   p_xianshi_goods表'   goods_id,store_id,goods_name,goods_image,goods_price,goods_freight,xianshi_price
     *            mansong   p_mansong表'         mansong_name,start_time,end_time,store_id
     *            bundling  p_bundling表'        bl_id,bl_name,bl_img,bl_discount_price,bl_freight_choose,bl_freight,store_id
     *            groupbuy  goods_group表'       group_id,group_name,goods_id,goods_price,groupbuy_price,group_pic,rebate,start_time,end_time
     *            coupon在后台发布
     */
    public function storeAutoShare($data, $type)
    {
        $param = array(
            3 => 'new',
            4 => 'coupon',
            5 => 'xianshi',
            6 => 'mansong',
            7 => 'bundling',
            8 => 'groupbuy'
        );
        $param_flip = array_flip($param);
        if (!in_array($type, $param) || empty($data)) {
            return false;
        }

        $auto_setting = Model('store_sns_setting')->getStoreSnsSettingInfo(array('sauto_storeid' => $_SESSION ['store_id']));
        $auto_sign = false; // 自动发布开启标志

        if ($auto_setting['sauto_' . $type] == 1) {
            $auto_sign = true;
            if (CHARSET == 'GBK') {
                foreach ((array)$data as $k => $v) {
                    $data[$k] = Language::getUTF8($v);
                }
            }
            $goodsdata = addslashes(json_encode($data));
            if ($auto_setting['sauto_' . $type . 'title'] != '') {
                $title = $auto_setting['sauto_' . $type . 'title'];
            } else {
                $auto_title = 'nc_store_auto_share_' . $type . rand(1, 5);
                $title = Language::get($auto_title);
            }
        }
        if ($auto_sign) {
            // 插入数据
            $stracelog_array = array();
            $stracelog_array['strace_storeid'] = $this->store_info['store_id'];
            $stracelog_array['strace_storename'] = $this->store_info['store_name'];
            $stracelog_array['strace_storelogo'] = empty($this->store_info['store_avatar']) ? '' : $this->store_info['store_avatar'];
            $stracelog_array['strace_title'] = $title;
            $stracelog_array['strace_content'] = '';
            $stracelog_array['strace_time'] = TIMESTAMP;
            $stracelog_array['strace_type'] = $param_flip[$type];
            $stracelog_array['strace_goodsdata'] = $goodsdata;
            Model('store_sns_tracelog')->saveStoreSnsTracelog($stracelog_array);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 商家消息数量
     */
    private function checkStoreMsg()
    {//判断cookie是否存在
        $cookie_name = 'storemsgnew_num' . session('seller_id');
        if (cookie($cookie_name) != null && intval(cookie($cookie_name)) >= 0) {
            $countnum = intval(cookie($cookie_name));
        } else {
            $where = array();
            $where['store_id'] = session('seller_id');
            $where['sm_readids'] = array('exp', 'sm_readids NOT LIKE \'%,' . session('seller_id') . ',%\' OR sm_readids IS NULL');
            if (session('seller_smt_limits') !== false) {
                $where['smt_code'] = array('in', session('seller_smt_limits'));
            }
            $countnum = Model('store_msg')->getStoreMsgCount($where);
            var_dump($countnum);
            die;
            cookie($cookie_name, intval($countnum), 2 * 3600);//保存2小时
        }
        $this->assign('store_msg_num', $countnum);
    }

}